package com.chaopei.dao.impl;

import com.chaopei.dao.StudentBaseDao;
import com.chaopei.entity.StudentBase;
import com.chaopei.utils.MyTools;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Corday 天涯
 * @Date 2022/3/24 10:29
 */
public class StudentBaseDaoImpl implements StudentBaseDao {
    //实现数据库的CURD
    @Override
    public List<StudentBase> selectAllStus() {
        Connection connection = MyTools.getConn();
        PreparedStatement ps =null;
        String sql="select * from student_base";
        List<StudentBase> stus=null;
        try {
            //进行事务管理
            //设置事务管理不自动提交
            connection.setAutoCommit(false);
            ps=connection.prepareStatement(sql);
            //执行后，生成结果对象,默认情况下集合对象rs的指针指向头部
            ResultSet rs = ps.executeQuery();
           stus = new ArrayList<>();
           while (rs.next()){
               //传参：字段索引号(从1开始)或字段名称
              int sid=rs.getInt("sid");
              String name=rs.getString("name");
              String gender=rs.getString("gender");
              Date birth=rs.getDate("birth");
              StudentBase stub=new StudentBase(sid,name,gender,birth);
              //保存到集合对象
              stus.add(stub);
           }
           //提交事务,保证数据的安全
            connection.commit();
           //关闭数据库连接
            MyTools.closeConn(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return stus;
    }

    @Override
    public int insertStu(StudentBase stu) {
        Connection connection = MyTools.getConn();
        PreparedStatement ps =null;
        String sql="insert into student_base(name,gender,birth) values(?,?,?)";
        int flag=0;
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1,stu.getName());
            ps.setString(2,stu.getGender());
            ps.setDate(3,stu.getBirth());
            flag = ps.executeUpdate();
            //关闭连接
            MyTools.closeConn(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }
}
